package com.alm.token.ui.fragmentDialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alm.token.ConStant;
import com.alm.token.GlideApp;
import com.alm.token.R;
import com.alm.token.base.BaseBehavior;
import com.alm.token.ui.activity.BlockWalletLoginActivity;
import com.alm.token.ui.data.bean.BuyHMioAddData;
import com.alm.token.ui.data.bean.BuyHMioTransIndexData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.BuyHMioView;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import baibeiwallet.event.getUserWalletEvent;
import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 作者：
 * 时间： 2017/9/18
 * 描述：    测试1
 */

public class BuyHMioSubmitFragment extends BaseDialogFragment implements BuyHMioView<BuyHMioTransIndexData>, TextWatcher, View.OnClickListener {

    ImageView imgBizhong1icon;
    TextView tv_top1show;
    TextView tvBizhong1tv;
    ImageView imgBizhong2icon;
    TextView tvBizhong2tv;
    TextView tvMoneyMax;
    EditText edtInputnumber;
    EditText edtMathnumber;
    TextView tvMathmoney;
    TextView tvOutmoneycommit;
    TextView tvJiaoyifeiMath;
    ImageView imgChangebizhong;
    TextView tvBizhong1Price;
    TextView tvBizhong2Price;
    TextView tvBizhong1Money;
    TextView tvBizhong2Money;
    LinearLayout lyMoneytyep1,ly_body;
    View viewTop, viewBottom;
    public List<BuyHMioTransIndexData.DataBean.WalletsBean> wallets = new ArrayList<>();
    BuyHMioTransIndexData.DataBean.WalletsBean walletsBean;
    BuyHMioTransIndexData.DataBean dataBean;
    private double number = 0d;
    private int bizhongType1 = 0;
    ClickListener clickListener;

    protected BaseBehavior behavior;

    protected MyPreenter preenter;
    protected MyPreenter updataPrenter;

    Activity mContext;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_transform;
    }

    @Override
    protected void initView(Dialog dialog) {
        ly_body= dialog.findViewById(R.id.ly_body);
        viewTop = dialog.findViewById(R.id.view_top);
        viewBottom = dialog.findViewById(R.id.view_bottom);
        imgBizhong1icon = dialog.findViewById(R.id.img_bizhong1icon);
        tv_top1show = dialog.findViewById(R.id.tv_top1show);
        tvBizhong1tv = dialog.findViewById(R.id.tv_bizhong1tv);
        imgBizhong2icon = dialog.findViewById(R.id.img_bizhong2icon);
        tvBizhong2tv = dialog.findViewById(R.id.tv_bizhong2tv);
        tvMoneyMax = dialog.findViewById(R.id.tv_moneymax);
        edtInputnumber = dialog.findViewById(R.id.edt_inputnumber);
        edtMathnumber = dialog.findViewById(R.id.edt_mathnumber);
        tvMathmoney = dialog.findViewById(R.id.tv_mathmoney);
        tvOutmoneycommit = dialog.findViewById(R.id.tv_outmoneycommit);
        tvJiaoyifeiMath = dialog.findViewById(R.id.tv_jiaoyifeimath);
        imgChangebizhong = dialog.findViewById(R.id.img_changebizhong);
        tvBizhong1Price = dialog.findViewById(R.id.tv_bizhong1price);
        tvBizhong2Price = dialog.findViewById(R.id.tv_bizhong2price);
        tvBizhong1Money = dialog.findViewById(R.id.tv_bizhong1money);
        tvBizhong2Money = dialog.findViewById(R.id.tv_bizhong2money);
        lyMoneytyep1 = dialog.findViewById(R.id.ly_moneytyep1);
        tv_top1show.setText(getString(R.string.tv_hint_activity_order_paysubmit) + "  (USDT)");
        viewTop.setOnClickListener(this);
        viewBottom.setOnClickListener(this);
        ly_body.setOnClickListener(this);
        initPreenter();
        initVariables();
        changView();
    }

    protected MyPreenter initPreenter() {
        return preenter = new MyPreenter(this);
    }

    protected void initVariables() {
        behavior = new BaseBehavior.SimpleBehavior(this);
        wallets.addAll(getDialogBean().getWallets());
        dataBean = getDialogBean().getDataBean();
        mContext = getDialogBean().getContext();
    }

    private void changView() {
        if (EmptyUtils.isNotEmpty(wallets)) {
            walletsBean = wallets.get(bizhongType1);

            GlideApp.with(this).load(walletsBean.getLogo())
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                            if (EmptyUtils.isNotEmpty(resource)) {
//                                CommonUtil. changeSVGColor(TransformActivity.this, imgBizhong1icon, resource, R.color.black);
//                                return true;
//                            }
                            return false;
                        }
                    }).error(R.drawable.icon_arctic).into(imgBizhong1icon);
            GlideApp.with(this).load(dataBean.getIcon())
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                            if (EmptyUtils.isNotEmpty(resource)) {
//                                CommonUtil. changeSVGColor(TransformActivity.this, imgBizhong2icon, resource, R.color.black);
//                                return true;
//                            }
                            return false;
                        }
                    }).error(R.drawable.icon_arctic).into(imgBizhong2icon);

            tvBizhong1tv.setText(walletsBean.getName());
            tvBizhong2tv.setText(dataBean.getName());

            edtInputnumber.addTextChangedListener(this);
            number = 0d;
            edtInputnumber.setText("");
            mathNumber(number);
        }

        tvOutmoneycommit.setOnClickListener(this);
        tvMoneyMax.setOnClickListener(this);
        lyMoneytyep1.setOnClickListener(this);
    }

    double money = 0.0000d;

    public void mathNumber(double number) {
        tvBizhong1Money.setText(CommonUtil.saveToPoint4WithNo(walletsBean.getMoney()) + " " + walletsBean.getName());
//        tvBizhong1Price.setText(getString(R.string.transform_hint_exchangerate)
//                + ("\t1 " + walletsBean.getName()
//                + " ≈ " + walletsBean.getPrice() + "$"));
        tvBizhong1Price.setText("1 USDT ≈ " + CommonUtil.saveToPoint4WithNo(1 / walletsBean.getPrice()) + " " + walletsBean.getName());

//        tvBizhong1Price.setText(dec1.format(walletsBeans.get(bizhongType1).getPrice()) + "USD");
//        tvBizhong2Price.setText(dec1.format(walletsBeans.get(bizhongType2).getPrice()) + "USD");
        money = number;
        tvMathmoney.setText("≈$" + CommonUtil.saveToPoint4WithNo4(money) + "/"
                + CommonUtil.saveToPoint4WithNo(money / walletsBean.getPrice()) + walletsBean.getName());

        edtMathnumber.setText(CommonUtil.saveToPoint4WithNo(money / dataBean.getPrice()));
//        edtMathnumber.setText(dec1.format((money - money * pro) / walletsBeans.get(bizhongType2).getPrice()));
    }

    @Override
    public int setThemeRes() {
        return R.style.BottomDialogFragment1;
    }

    private boolean outSidedismiss = true;

    @Override
    protected void setView() {
        dialog.setCanceledOnTouchOutside(outSidedismiss);
        final Window window = dialog.getWindow();
        final WindowManager.LayoutParams lp = window.getAttributes();
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.gravity = Gravity.CENTER;

        window.setAttributes(lp);
        if (!outSidedismiss) {
            getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    return keyCode == KeyEvent.KEYCODE_BACK;
                }
            });
        }
//        setCanceledOnTouchOutside(true);
    }

    public void setListener(ClickListener clickListener) {
        this.clickListener = clickListener;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence s, int i, int i1, int i2) {
        if (s.toString().contains(".")) {
            if (s.length() - 1 - s.toString().indexOf(".") > 4) {
                s = s.toString().subSequence(0, s.toString().indexOf(".") + 5);
                edtInputnumber.setText(s);
                edtInputnumber.setSelection(s.length());
            }
        }
        if (s.toString().trim().substring(0).equals(".")) {
            s = "0" + s;
            edtInputnumber.setText(s);
            edtInputnumber.setSelection(2);
        }

        if (s.toString().startsWith("0")
                && s.toString().trim().length() > 1) {
            if (!s.toString().substring(1, 2).equals(".")) {
                edtInputnumber.setText(s.subSequence(0, 1));
                edtInputnumber.setSelection(1);
                return;
            }
        }

        number = Double.parseDouble(s != null ? (!s.toString().isEmpty() ? s.toString() : "0") : "0");

        if (number > walletsBean.getMoney() * walletsBean.getPrice()) {
            showToast(getString(R.string.conversioncurrency_hint1_warn6));
//            if (walletsBeans.get(bizhongType1).getMoney() > 10000d) {
//                number = 10000d;
//            } else {
//                number = walletsBeans.get(bizhongType1).getMoney();
//            }
            edtInputnumber.setText("");
            return;
        }
        mathNumber(number);
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    @Override
    public void getBuyHMioAddOrder(BuyHMioAddData buyHMioAddData) {
        showToast(buyHMioAddData.getMsg());
        if (buyHMioAddData.getStatus() == 0) {
            EventBus.getDefault().post(new getUserWalletEvent(null));
            dismissParent();
        }
    }

    @Override
    public void getData(BuyHMioTransIndexData buyHMioTransIndexData) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        showToast(getString(R.string.common_loaderrritry));
        dismissParent();
    }

    @Override
    public void onError(String error) {
        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {
        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }

    //     EventBus.getDefault().post(new getUserWalletEvent(null));
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserWalletEvent1(getUserWalletEvent userWalletEvent) {

    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);

        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onClick(View view) {

        if (wallets.size() == 0)
            return;

        switch (view.getId()) {
            case R.id.view_top:
            case R.id.view_bottom:
            case R.id.ly_body:
                dismissParent();
                break;
            case R.id.tv_moneymax:
                number = Double.valueOf(CommonUtil.saveToPoint4WithNo4(walletsBean.getMoney() * walletsBean.getPrice()));
                edtInputnumber.setText(number + "");
                mathNumber(number);
                break;


            case R.id.ly_moneytyep1:
                if (EmptyUtils.isNotEmpty(wallets)) {
                    if (EmptyUtils.isNotEmpty(popWindow)) {
                        popWindow.dismiss();
                        popWindow = null;
                    }
                    showPopwindow();
                }

                break;

            case R.id.img_changebizhong:
                break;
            case R.id.tv_outmoneycommit:

//                if (clickListener != null) {
//                    clickListener.Listener("", 0);
//                }
//                dismissParent();


                if (number == 0) {
                    showToast(getString(R.string.hmio_hint_inputmoneywarm));
                    break;
                }

//                if (wallets != null && wallets.size() != 0 && walletsBean.isChange()) {//可兑换
                    UserWalletData.DataBean.SysMsgBean sysMsgBean = new UserWalletData.DataBean.SysMsgBean();
                    sysMsgBean.setTitle(getString(R.string.conversioncurrency_hint1_warn4));
                    sysMsgBean.setContent(
                            getString(R.string.conversioncurrency_hint1_warn8, CommonUtil.saveToPoint4WithNo(number / walletsBean.getPrice()),
                                    "" + tvBizhong1tv.getText().toString(), tvBizhong2tv.getText().toString()));
                    DialogUtils.showInfor1(mContext, sysMsgBean, (pwd) -> {

                        DialogUtils.enterPayPsw(mContext, (pwd1) -> {

                            //eth1 mio2
                            preenter.getHMioAddOrderData(number + "", walletsBean.getId() + "", pwd1);
                        });
                    });
//                } else {
//                    showToast(getString(R.string.conversioncurrency_hint1_warn5));
//                }
                break;
        }

    }

    public interface ClickListener {
        void Listener(String name, int potion);
    }


    PopupWindow popWindow;

    private void showPopwindow() {
        View parent = ((ViewGroup) dialog.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(dialog.getContext(), R.layout.view_pop_selecter, null);
        LinearLayout ly_pop_body = popView.findViewById(R.id.ly_pop_body);


        for (int i = 0; i < wallets.size(); i++) {
            BuyHMioTransIndexData.DataBean.WalletsBean coinBean = wallets.get(i);

            View itemView = View.inflate(dialog.getContext(), R.layout.item_pop_wallet, null);
            GlideApp.with(this)
                    .load(coinBean.getLogo())
                    .error(R.drawable.icon_arctic)
                    .into((ImageView) itemView.findViewById(R.id.img_bizhongicon));
            ((TextView) itemView.findViewById(R.id.name)).setText(coinBean.getName());
            ((TextView) itemView.findViewById(R.id.desc)).setVisibility(View.INVISIBLE);

            ((TextView) itemView.findViewById(R.id.money1)).setText(CommonUtil.saveToPoint4WithNo(coinBean.getMoney()));
            ((TextView) itemView.findViewById(R.id.money2)).setVisibility(View.INVISIBLE);

            int finalI = i;
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bizhongType1 = finalI;
                    changView();
                    popWindow.dismiss();
                }
            });
            ly_pop_body.addView(itemView);

        }

        ly_pop_body.setBackgroundColor(getResources().getColor(R.color.text_cccccc));


        RelativeLayout outside = popView.findViewById(R.id.pop_outside);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        if (popWindow == null) {
            popWindow = new PopupWindow(popView, width, height);
            popWindow.setAnimationStyle(R.style.BottomToTopAnim);
//        popWindow.setFocusable(true);
            popWindow.setOutsideTouchable(true);// 设置同意在外点击消失
        }
        outside.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });

        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void showToast(@StringRes int resId) {
        if (behavior != null) {
            behavior.showToast(resId);
        }
    }

    public void showToast(String msg) {
        if (behavior != null) {
            behavior.showToast(msg);
        }
    }

    public void showWaitDialog() {
        if (behavior != null) {
            behavior.showWaitDialog();
        }
    }

    public void hideWaitDialog() {
        if (behavior != null) {
            behavior.hideWaitDialog();
        }
    }

}